package org.trc.network;

import java.awt.Rectangle;

/**
 * 
 * @author Lin Xu
 * 
 */

public abstract class Graphable {

	Rectangle mbr;

	public abstract String getID();

	public Graphable() {
	}

	public Rectangle getMBR() {
		return mbr;
	}

	public Object getType() {
		return (Object) getClass();
	}

	/**
	 * Computes the distance between two points.
	 * 
	 * @return distance
	 */
	public static double computeDistance(int x1, int y1, int x2, int y2) {
		long xDist = Math.abs(x1 - x2);
		long yDist = Math.abs(y1 - y2);
		return Math.sqrt(xDist * xDist + yDist * yDist);
	}

	/**
	 * Computes the distance of the drawing primitive to a point.
	 * 
	 * @return distance
	 */
	public double computeDistanceTo(int x, int y) {
		Rectangle mbr = getMBR();
		return computeDistance(mbr.x + mbr.width / 2, mbr.y + mbr.height / 2,
				x, y);
	}

	/**
	 * Tests whether the primitive is selected by a given point or not. The
	 * default implementation is based on the mbr of the primitive.
	 * 
	 * @return selected?
	 */
	public boolean interacts(int x, int y) {
		return getMBR().contains(x, y);
	}

	/**
	 * Tests whether the drawable primitive intersects another primitive. The
	 * default implementation is based on the mbr of the primitive.
	 * 
	 */
	public boolean intersects(Graphable graphCom) {
		if (graphCom == null) {
			return false;
		} else {
			return intersects(graphCom.getMBR());
		}
	}

	/**
	 * Tests whether the drawable primitive intersects a given rectangle. The
	 * default implementation is based on the mbr of the primitive.
	 * 
	 * @return intersects?
	 * @param r
	 *            the rectangle
	 */
	public boolean intersects(Rectangle r) {
		return getMBR().intersects(r);
	}

	/**
	 * Tests whether the drawable primitive intersects another primitive which
	 * is passed as Object.
	 * 
	 * @return intersect?
	 * @param prim
	 *            the other drawable primitive
	 */
	public boolean intersects(Object prim) {
		if ((prim == null) || !getClass().isInstance(prim)) {
			return false;
		}
		return intersects((Graphable) prim);
	}

	/**
	 * Tests whether the drawable primitive is contained by a given rectangle.
	 * The default implementation is based on the mbr of the primitive.
	 * 
	 * @return is contained?
	 * @param rect
	 *            the rectangle
	 */
	public boolean isContainedBy(Rectangle rect) {
		if (rect == null) {
			return false;
		} else {
			return rect.contains(getMBR());
		}
	}

}
